package com.yxkj.syh.app.huarong.activities.workbench;


import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.syh.app.basic.base.BaseFragment;
import com.syh.app.basic.utils.ComUtil;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.adps.TaskListAdp;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.PagesRequest;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.constants.OrderStatus;
import com.yxkj.syh.app.huarong.databinding.FragmentWorkbenchBinding;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 工作台
 */
public class WorkbenchFragment extends BaseFragment<FragmentWorkbenchBinding, WorkbenchVM> {
    private PagesRequest ordersRequest;
    private TaskListAdp mTaskListAdp;

    public WorkbenchFragment() {
    }

    public static WorkbenchFragment newInstance() {
        WorkbenchFragment fragment = new WorkbenchFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getViewModelId() {
        return BR.workbenchVM;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_workbench;
    }

    @Override
    protected void initView() {
        mTaskListAdp = new TaskListAdp();
        mVDBinding.rvTask.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false));
        mTaskListAdp.bindToRecycleView(mVDBinding.rvTask);
        mTaskListAdp.setOnViewClick(new TaskListAdp.OnViewClick() {
            @Override
            public void onItem(OrderInfo orderInfo) {
                ARouter.getInstance().build(ArouterPath.ORDER_STATUS1_ACTIVITY).withLong("orderId", orderInfo.getId()).navigation();
            }

            @Override
            public void onReturnGoods(OrderInfo orderInfo) {
                ARouter.getInstance().build(ArouterPath.RETURN_GOODS_ACTIVITY).withSerializable("orderInfo", orderInfo).navigation();
            }

            @Override
            public void onReceiveGoods(OrderInfo orderInfo) {
                ARouter.getInstance().build(ArouterPath.RECEIVE_ACTIVITY).withLong("orderID", orderInfo.getId()).navigation();
            }
        });

        mVDBinding.srlTask.setOnRefreshListener(refreshLayout -> {
            initData();
        });

        mVDBinding.srlTask.setOnLoadMoreListener(refreshLayout -> {
            ordersRequest.setPageIndex(ordersRequest.getPageIndex().intValue() + 1);
            mViewModel.getOrderList(ordersRequest);
        });
        mVDBinding.srlTask.setEnableLoadMore(false);

        mVDBinding.llStartDate.setOnClickListener(v -> {

            chooseDate(0);
        });
        mVDBinding.llEndDate.setOnClickListener(v -> {

            chooseDate(1);
        });

        mVDBinding.ivClearEt.setOnClickListener(v -> {
            mVDBinding.etCarKey.setText("");
            mVDBinding.etCarKey.clearFocus();
            reTaskList();
        });

        mVDBinding.etCarKey.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击搜索的时候隐藏软键盘
                hideKeyboard(mVDBinding.etCarKey);
                // 在这里写搜索的操作,一般都是网络请求数据

                reTaskList();

                return true;
            }
            return false;
        });
        mVDBinding.tvQuery.setOnClickListener(v -> {
            hideKeyboard(mVDBinding.etCarKey);
            reTaskList();
        });

        if (mCalendarStart == null) {
            mCalendarStart = Calendar.getInstance();
            mCalendarStart.setTimeInMillis(System.currentTimeMillis());

            mCalendarStart.set(Calendar.HOUR_OF_DAY, 0);
            mCalendarStart.set(Calendar.MINUTE, 0);
            mCalendarStart.set(Calendar.SECOND, 0);

            //防止mysql自动加一秒,毫秒设为0
            mCalendarStart.set(Calendar.MILLISECOND, 0);
        }
        if (mCalendarEnd == null) {
            mCalendarEnd = Calendar.getInstance();
            mCalendarEnd.setTimeInMillis(System.currentTimeMillis());

            mCalendarEnd.set(Calendar.HOUR_OF_DAY, 23);
            mCalendarEnd.set(Calendar.MINUTE, 59);
            mCalendarEnd.set(Calendar.SECOND, 59);

            //防止mysql自动加一秒,毫秒设为0
            mCalendarEnd.set(Calendar.MILLISECOND, 999);
        }
//        String dateStr = mCalendarStart.get(Calendar.YEAR) + "年" + (mCalendarStart.get(Calendar.MONTH) + 1) + "月" + mCalendarStart.get(Calendar.DAY_OF_MONTH) + "日";
        String dateStr = "起始时间";
        mVDBinding.tvStartDate.setText(dateStr);
        String dateStr2 = mCalendarEnd.get(Calendar.YEAR) + "年" + (mCalendarEnd.get(Calendar.MONTH) + 1) + "月" + mCalendarEnd.get(Calendar.DAY_OF_MONTH) + "日";
        mVDBinding.tvEndDate.setText(dateStr2);

    }

    private boolean isDefStartTime = true;

    @Override
    protected void initData() {

        reTaskList();
        mViewModel.report();
    }

    private void reTaskList() {
        ordersRequest = new PagesRequest();
        ordersRequest.setPageIndex(1);
        ordersRequest.setPageSize(10);
        ordersRequest.setSortFields("id_d");

        List<PagesRequest.SqlParam> sqlParams = new ArrayList<>();

        //状态
        PagesRequest.SqlParam sqlStatusParam = new PagesRequest.SqlParam();
        sqlStatusParam.setValue(OrderStatus.WAIT_ECEIVING);
        sqlStatusParam.setKey("o.status");
        sqlStatusParam.setOper("=");
        sqlParams.add(sqlStatusParam);

        //时间段
        if (!isDefStartTime) {
            PagesRequest.SqlParam sqlTimeParam = new PagesRequest.SqlParam();
            String time = ComUtil.formatDate3(null, mCalendarStart.getTime()) + "," + ComUtil.formatDate3(null, mCalendarEnd.getTime());
            sqlTimeParam.setValue(time);
            sqlTimeParam.setKey("o.createTime");
            sqlTimeParam.setOper("b");
            sqlParams.add(sqlTimeParam);
        }

        //车牌号
        String carId = mVDBinding.etCarKey.getText().toString();
        if (!TextUtils.isEmpty(carId)) {
            PagesRequest.SqlParam sqlCarParam = new PagesRequest.SqlParam();
            sqlCarParam.setValue(carId.trim());
            sqlCarParam.setKey("o.license");
            sqlCarParam.setOper(":");

            sqlParams.add(sqlCarParam);
        }

        ordersRequest.setQueryList(sqlParams);

        mViewModel.getOrderList(ordersRequest);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldOrderResponse.observe(this, orderInfos -> {
            if (mVDBinding.srlTask.isRefreshing()) {
                mVDBinding.srlTask.finishRefresh();
            } else if (mVDBinding.srlTask.isLoading()) {
                mVDBinding.srlTask.finishLoadMore();
            }

            if (orderInfos != null) {
                if (ordersRequest.getPageIndex() == 1) {
                    mTaskListAdp.setNewData(orderInfos.getRecords());
                } else {
                    mTaskListAdp.addAll(orderInfos.getRecords());
                }
                if (ordersRequest.getPageIndex() < orderInfos.getPages()) {
                    mVDBinding.srlTask.setEnableLoadMore(true);
                } else {
                    mVDBinding.srlTask.setEnableLoadMore(false);
                }
            }
        });
    }


    private Calendar mCalendarStart, mCalendarEnd;


    /**
     * 选择日期
     *
     * @param type 0 起始日期   1   终止日期
     */
    private void chooseDate(int type) {

        Calendar calendar;

        if (type == 0) {
            calendar = mCalendarStart;
        } else {
            calendar = mCalendarEnd;
        }

        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dialog = new DatePickerDialog(getActivity(), (view, year1, month, dayOfMonth1) -> {

            if (type == 0) {
                mCalendarStart.set(Calendar.YEAR, year1);
                mCalendarStart.set(Calendar.MONTH, month);
                mCalendarStart.set(Calendar.DAY_OF_MONTH, dayOfMonth1);

                String dateStr = year1 + "年" + (month + 1) + "月" + dayOfMonth1 + "日";
                mVDBinding.tvStartDate.setText(dateStr);
                if (isDefStartTime) isDefStartTime = false;
            } else if (type == 1) {
                mCalendarEnd.set(Calendar.YEAR, year1);
                mCalendarEnd.set(Calendar.MONTH, month);
                mCalendarEnd.set(Calendar.DAY_OF_MONTH, dayOfMonth1);

                if (mCalendarStart.getTimeInMillis() > mCalendarEnd.getTimeInMillis()) {
                    mCalendarStart.set(Calendar.YEAR, year1);
                    mCalendarStart.set(Calendar.MONTH, month);
                    mCalendarStart.set(Calendar.DAY_OF_MONTH, dayOfMonth1);

                    String dateStr = year1 + "年" + (month + 1) + "月" + dayOfMonth1 + "日";
                    mVDBinding.tvStartDate.setText(dateStr);
                    if (isDefStartTime) isDefStartTime = false;
                }

                String dateStr = year1 + "年" + (month + 1) + "月" + dayOfMonth1 + "日";
                mVDBinding.tvEndDate.setText(dateStr);
            }

            reTaskList();

        }, year, monthOfYear, dayOfMonth);
        if (type == 0) {
            dialog.getDatePicker().setMaxDate(mCalendarEnd.getTimeInMillis());
        } else {
            dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        }
        dialog.show();
    }


    @Override
    protected void visibleAgain() {
        initData();
    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     */
    public void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}
